package com.mmall.common;

import com.mmall.utils.PropertiesUtil;
import redis.clients.jedis.*;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.ArrayList;
import java.util.List;

/**
 * redis分布式缓存，
 * shard碎片
 */
public class ShardedRedisPool {

    private static ShardedJedisPool pool;//jedis连接池

    //最大连接数
    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20"));

    //最大空闲的实例
    private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "10"));

    //在pool中最小idle状态的实例
    private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle", "2"));

    //在borrow一个实例的时候，是否测试，如果赋值为true，则得到的实例时可用的，
    private static boolean testOnBorrow = Boolean.valueOf(PropertiesUtil.getProperty("redis.test.borrow", "true"));

    //在return一个实例的时候，是否测试，如果赋值为true，则得到的实例时可用的，
    private static boolean testOnReturn = Boolean.valueOf(PropertiesUtil.getProperty("redis.test.return", "true"));

    private static String ip1 = PropertiesUtil.getProperty("redis1.ip");

    private static Integer port1 = Integer.parseInt(PropertiesUtil.getProperty("redis1.port"));

    private static String ip2 = PropertiesUtil.getProperty("redis2.ip");

    private static Integer port2 = Integer.parseInt(PropertiesUtil.getProperty("redis2.port"));

    private static void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        //连接耗尽的是否，是否阻塞，默认为true
        config.setBlockWhenExhausted(true);

        JedisShardInfo info1 = new JedisShardInfo(ip1, port1, 100 * 2);
        //如果有密码，
        //info1.setPassword("password");

        JedisShardInfo info2 = new JedisShardInfo(ip2, port2, 100 * 2);

        List<JedisShardInfo> jedisShardInfoList = new ArrayList<>(2);

        jedisShardInfoList.add(info1);
        jedisShardInfoList.add(info2);

        //创建分布式redis池
        pool = new ShardedJedisPool(config, jedisShardInfoList, Hashing.MURMUR_HASH,
                Sharded.DEFAULT_KEY_TAG_PATTERN);
    }

    static {
        initPool();
    }

    /**
     * 得到连接池中的jedis
     * @return
     */
    public static ShardedJedis getResource() {
        return pool.getResource();
    }


    public static void main(String[] args) {
        ShardedJedis jedis = getResource();
//        for (int i = 0; i < 10; i++) {
//            jedis.set("zhikey" + i, "zhivalue"+i);
//        }
//        jedis.close();
        String value = jedis.get("zhikey3");
        System.out.println("value:"+value);
        System.out.println(" program is end");


    }

}
